package com.woniu.realm;

import com.woniu.service.UserService;
import com.woniu.service.impl.UserServiceImpl;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Set;

/**
 * @author zhaolei
 * @date 2021/4/22 - 23:34
 */
public class myRealm extends AuthorizingRealm {
    private UserService userService;

    public myRealm() {
        this.userService = new UserServiceImpl();
    }

    @Override
    public String getName() {
        return "myRealm";
    }

    /**
     * 做授权处理
     * @param principalCollection
     * @return info
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户名,因为获取role和permission时要用到用户名
        String userName = (String) principalCollection.getPrimaryPrincipal();
        //利用userName获取到角色名的集合
        Set<String> rolesByUserName = this.userService.getRolesByUserName(userName);
        //利用userName获取到该用户所拥有的的权限的集合
        Set<String> permissionsByUserName = this.userService.getPermissionsByUserName(userName);
        //实例化一个SimpleAuthorizationInfo对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //将查询出来的该用户角色名的集合赋值给SimpleAuthorizationInfo
        info.setRoles(rolesByUserName);
        //将查询出来的该用户权限的集合赋值给SimpleAuthorizationInfo
        info.setStringPermissions(permissionsByUserName);
        return info;
    }

    /**
     * 做认证操作
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        /***
         * SimpleAuthenticationInfo(Object principal, Object credentials, String realmName)
         * 三个参数分别对应：①用户名  ②密码  ③realm名称
         * 用户名获取：String userName = (String) authenticationToken.getPrincipal();
         * 密码获取:String pwd = this.userService.getPwdByUserName(user);
         * realm名称获取：String realmName = this.getName();
         */
        String user = (String) authenticationToken.getPrincipal();
        String pwd = this.userService.getPwdByUserName(user);
        String realmName = this.getName();
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user,pwd,realmName);
        return simpleAuthenticationInfo;
    }
}
